package com.example.saifly.mainPage.record;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.cardview.widget.CardView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Application.MyApplication;
import com.example.common.Fragment;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.R;
import com.example.saifly.inPageRecord.BodyDataActivity;
import com.example.saifly.inPageRecord.DisplayRecordActivity;
import com.example.saifly.inPageRecord.EnvironmentActivity;
import com.example.saifly.inPageRecord.RecordModel.BodyData;
import com.example.saifly.inPageRecord.RecordModel.TotalScore;
import com.hb.dialog.myDialog.MyAlertInputDialog;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class RecordFragment extends Fragment {

    private RelativeLayout rlBody,rlEnvironment;
    private CardView scoreCard;
    private static SharedPreferences sharedPreferences= MyApplication.getContext().getSharedPreferences("config",Context.MODE_PRIVATE);
    private static TextView tvScore,tvScoreComment,tvTime,tvStep;
    private BodyData bodyData=new BodyData();


    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_record;
    }

    @Override
    protected void init() {
        super.init();
        scoreCard=getActivity().findViewById(R.id.record_score_card);
        rlBody=getActivity().findViewById(R.id.record_body_card_show);
        rlEnvironment=getActivity().findViewById(R.id.record_environment_card_show);
        tvScore=getActivity().findViewById(R.id.record_score);
        tvScoreComment=getActivity().findViewById(R.id.record_score_comment);
        tvTime=getActivity().findViewById(R.id.record_time);
        tvStep=getActivity().findViewById(R.id.record_step);
        initClick();
        updateUi();


    }

    private void initClick(){
        String user = sharedPreferences.getString("identity","default");
        Log.d("user", "initClick: "+user);

            Log.d("user", "initClick: "+user);
            tvStep.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(user.equals("patient"))
                    {
                        final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(getContext()).builder()
                                .setTitle("请输入")
                                .setEditText("");
                        myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                int temp = 0;
                                for (int i = 0; i < myAlertInputDialog.getResult().length(); i++) {
                                    if (myAlertInputDialog.getResult().charAt(i) >= '0' && myAlertInputDialog.getResult().charAt(i) <= '9') {

                                    } else {
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(getActivity(), "步数格式不正确", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                        temp = 1;
                                    }
                                }
                                if (temp == 0) {
                                    int hearttemp = Integer.parseInt(myAlertInputDialog.getResult());
                                    tvStep.setText(String.valueOf(hearttemp));
                                    bodyData.setStepCount(Integer.valueOf(myAlertInputDialog.getResult()));
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            UpdateStepData(bodyData);
                                        }
                                    }).start();
                                    myAlertInputDialog.dismiss();
                                }

                            }
                        }).setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                myAlertInputDialog.dismiss();
                            }
                        });
                        myAlertInputDialog.show();
                    }
                }

            });


        scoreCard.setOnClickListener(v -> startActivity(new Intent(getContext(), DisplayRecordActivity.class)));
        rlBody.setOnClickListener(v-> startActivity(new Intent(getContext(), BodyDataActivity.class)));
        rlEnvironment.setOnClickListener(v-> startActivity(new Intent(getContext(), EnvironmentActivity.class)));
    }




    public static void reloadData(){
    }

    @Override
    public void onStart() {
        super.onStart();
        updateUi();
        tvTime.setText(sharedPreferences.getString("time","暂无数据"));
    }

    public void updateUi()
    {
        new Thread(new Runnable() {
            @Override
            public void run()
            {
                getTotalScore();
            }
        }).start();
        SharedPreferences sharedPreferences = MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        String phoneNum = sharedPreferences.getString("uid","default");
        Date date = new Date();

        new Thread(new Runnable() {
            @Override
            public void run()
            {
                GetStepData(phoneNum,date);
            }
        }).start();


    }

    private interface ApiGetDisplayData {
        //获取最近一次总分；
        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getTop1TotalScore")
        Call<ResponseBody> GetTotalScore(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/estimate/getBodyData")
        Call<ResponseBody> GetStepData(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/plan/submitBodyData")
        Call<ResponseBody> UpdateStepData(@Body JSONObject jsonObject);
    }


    private void getTotalScore()
    {
        String patientPhone =sharedPreferences.getString("uid","default");
        RetrofitHelper retrofitHelper= new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

        JSONObject jsonObject =new JSONObject();
        jsonObject.put("patientPhone",patientPhone);
        Call <ResponseBody> call = apiGetDisplayData.GetTotalScore(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    //  dailyQesFinish = (int) result.get("result");


                    if(result.getString("result").length()>1){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TotalScore totalScore = JSON.parseObject(result.getString("result"),TotalScore.class);
                                tvScore.setText(totalScore.getTotalScore().toString());
                                tvScoreComment.setText(analyse(totalScore.getTotalScore()));
                                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                String dateString = formatter.format(totalScore.getDate());
                                Log.d("dateString", "run: "+dateString);
                                tvTime.setText(dateString);
                                Log.d("totalscore", "run: ahjtahtdghs");
                            }
                        });

                    }
                    else
                    {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvScore.setText("0");
                                tvScoreComment.setText("新用户");
                                Log.d("totalscore", "run: ahjtahtdghs");
                            }
                        });

                    }
                }
                else{
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }

    }

    private void GetStepData(String phoneNum,Date date)
    {
        Long longDate =date.getTime();
        RetrofitHelper retrofitHelper =new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetDisplayData apiGetDisplayData = retrofit.create(ApiGetDisplayData.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("patientPhone",phoneNum);
        jsonObject.put("date",longDate);

        Call <ResponseBody> call = apiGetDisplayData.GetStepData(jsonObject);

        final Response<ResponseBody> response;

        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    //这里放正常流程操作
                    //  dailyQesFinish = (int) result.get("result");

                    JSONObject resultbodyData =result.getJSONObject("result");
                    String bodyDate=resultbodyData.getString("bodyData");
                    BodyData getbodyData =JSON.parseObject(bodyDate, BodyData.class);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d("bodydata", "run: "+bodyData.toString());

                            bodyData=getbodyData;
                            tvStep.setText(getbodyData.getStepCount().toString());

                        }
                    });
                }
                else{
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }


    }

    private void UpdateStepData(BodyData bodyData) {

            RetrofitHelper retrofitHelper=new RetrofitHelper();
            Retrofit retrofit=retrofitHelper.getRetrofit();
            ApiGetDisplayData apiGetDisplayData=retrofit.create(ApiGetDisplayData.class);

            JSONObject jsonObject=new JSONObject();
            String jsonString = JSON.toJSONString(bodyData);
            jsonObject.put("bodyData",jsonString);
            Log.d("bodyData", "BodySetData: "+jsonObject.toString());

            Call<ResponseBody> call=apiGetDisplayData.UpdateStepData(jsonObject);//请求
            final Response<ResponseBody> response;
            try {
                response = call.execute();
                if(response.body() != null){
                    JSONObject result=JSON.parseObject(response.body().string());
                    if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                        //这里放正常流程操作
                        //  dailyQesFinish = (int) result.get("result");
                    }
                    else{
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "网络出现异常", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            } catch (IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                    }
                });
                e.printStackTrace();
            }
    }

    private String analyse(float Score)
    {
        String temp;
        if(Score>80)
        {
            temp="整体身体状况优秀";
        }
        else if(Score>60)
        {
            temp="整体身体状况良好";
        }

        else if(Score>40)
        {
            temp="整体身体状况较差";
        }

        else
        {
            temp="整体身体状况很差";
        }
        return temp;

    }


}